import { v4 as uuid } from 'uuid'
import { StdNote, StdNoteTextDataV2 } from './note'
import store from '@/store'

class StdFigureCaption {
  constructor({ dataId, title }) {
    this.dataId = dataId || uuid()
    this.title = title
  }
}

class StdFigureAttr {
  constructor({ url, width, height }) {
    // 图片的链接
    this.url = url
    // 宽-单位像素
    this.width = width
    // 高-单位像素
    this.height = height
  }
}

export class StdFigureData {
  constructor({ dataId, figureNumber, attributes, captionZh, captionEn, xmlContent, noteList = [] }) {
    // 数据唯一标识
    this.dataId = dataId || uuid()
    // 图的编号-不参与是否修订，所以独立
    this.figureNumber = figureNumber
    // 基本属性
    this.attributes = attributes ? new StdFigureAttr(attributes) : null
    // 中文标题
    this.captionZh = captionZh ? new StdFigureCaption(captionZh) : null
    // 英文标题
    this.captionEn = captionEn ? new StdFigureCaption(captionEn) : null
    // 可编辑的图数据-比如流程图的xml数据
    this.xmlContent = xmlContent
    // 数据类型dataType = figure_note（图注）,figure_footnote（图脚注）
    this.noteList = noteList.map((i) => new StdNote(i))
  }
}

export class StdFigureV2 {
  constructor(node, number) {
    this.node = node
    this.number = number
  }
  get data() {
    return this.parseFigure(this.node, this.number)
  }
  parseFigure(block, figureNumber) {
    let notes = []
    // 解析图片结构化块中的图注和图脚注
    function getNotes(child) {
      if (child) {
        const attr = child.dataset || {}
        const dataType = attr.type
        if (dataType === 'figure_note' || dataType === 'figure_footnote') {
          notes.push({
            dataType,
            dataId: attr.noteId || uuid(),
            shareId: attr.shareId,
            referredId: attr.referredId || null,
            contentNumber: attr.number,
            dataLang: attr.lang,
            textData: new StdNoteTextDataV2(child, dataType).data
          })
        }
        if (child.nextSibling) {
          getNotes(child.nextSibling)
        }
      }
    }
    getNotes(block?.firstChild?.nextSibling)
    const rootAttr = block.dataset || {}
    const imgDom = block.querySelector('img') || {}
    const captionDomZh = block.querySelector('.data-content-image-caption.zh')
    const captionDomEn = block.querySelector('.data-content-image-caption.en')
    const figureData = {
      dataId: rootAttr.id,
      figureNumber,
      attributes: {
        url: imgDom.src || '',
        width: imgDom.width || 30,
        height: imgDom.height || 30
      },
      captionZh: {
        dataId: captionDomZh?.dataset?.id || '',
        title: captionDomZh?.textContent || ''
      },
      captionEn:
        store.getters.languageType === 'both'
          ? {
              dataId: captionDomEn?.dataset?.id || '',
              title: captionDomEn?.textContent || ''
            }
          : null,
      xmlContent: imgDom?.dataset?.drawioXml || '',
      noteList: notes
    }
    return figureData
  }
}
